// import 'package:date_time_picker_widget/date_time_picker_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_todolist/db/table/user_table.dart';
import 'package:flutter_todolist/helper/event/event_bus_name.dart';
import 'package:flutter_todolist/helper/event/event_helper.dart';
import 'package:flutter_todolist/pages/add_task_type/add_task_type.dart';
import 'package:flutter_todolist/pages/home/task_overview.dart';
import 'package:flutter_todolist/utils/common.dart';
import 'package:flutter_todolist/utils/extention.dart';
import 'package:flutter_todolist/utils/get_storage.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:omni_datetime_picker/omni_datetime_picker.dart';
import 'package:date_time_format/date_time_format.dart';

import '../../db/db.dart';
import '../../db/table/task_table.dart';
import '../../db/table/task_type_table.dart';
import '../../util.dart';
import '../../widgets/app_button.dart';
import '../../widgets/text_input.dart';
import '../home/task_controller.dart';
import '../home/task_type_controller.dart';

class AddTaskDialog extends Dialog {
  const AddTaskDialog({
    super.key,
  });

  @override
  Widget build(BuildContext context) {
    return const TaskAddContent();
  }

  Future show(BuildContext context) async {
    await showSlideDialog(context, const AddTaskDialog());
  }

}

class TaskAddContent extends StatefulWidget {
  const TaskAddContent({Key? key}) : super(key: key);

  @override
  State<TaskAddContent> createState() => _TaskAddContentState();
}

class _TaskAddContentState extends State<TaskAddContent> {

  List<String> subTasks = <String>['Call the restaurant ', 'Ask for the date '];
  late TaskTable taskTable;
  late Task newTask;

  TextEditingController taskTitleCtrl = TextEditingController();
  TaskController taskCtrl = Get.find<TaskController>();
  TaskTypeController taskTypeCtrl = Get.find<TaskTypeController>();
  TaskOverViewController taskOverViewController = Get.find<TaskOverViewController>();

  @override
  void initState() {
    taskTable = ToDoDB().taskTable;

    User userInfo = User.fromJson(AppStorage().read(AppStorage.UserInfo));
    newTask = Task(
      createTime: DateTime.now().millisecondsSinceEpoch,
      expiresTime: DateTime.now().millisecondsSinceEpoch,
      createBy: userInfo.userId
    );
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Align(
      child: Container(
        // height: MediaQuery.of(context).size.height - 80,
        // padding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
        margin: EdgeInsets.only(top: 80.h),
        child: Stack(
          alignment: AlignmentDirectional.topCenter,
          children: <Widget>[
            Positioned(
              // top: MediaQuery.of(context).size.height / 25,
              // top: 0,
              // bottom: 0,
              left: 0,
              child: Container(
                height: MediaQuery.of(context).size.height,
                // height: 800,
                width: MediaQuery.of(context).size.width,
                decoration: const BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.vertical(
                    top: Radius.elliptical(175, 30),
                  ),
                ),
              ),
            ),
            Positioned(
              top: 0,
              bottom: 0,
              left: 0,
              right: 0,
              child: Material(
                color: Colors.transparent,
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: <Widget>[
                    const SizedBox(height: 30),
                    close(),
                    content(),
                    addTask()
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget close() {
    return InkWell(
      onTap: () {
        Navigator.pop(context);
      },
      child: Container(
        width: 50,
        height: 50,
        decoration: const BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topLeft,
            end: Alignment.bottomRight,
            colors: <Color>[
              CustomColors.PurpleLight,
              CustomColors.PurpleDark,
            ],
          ),
          borderRadius: BorderRadius.all(
            Radius.circular(50.0),
          ),
          boxShadow: [
            BoxShadow(
              color: CustomColors.PurpleShadow,
              blurRadius: 10.0,
              spreadRadius: 5.0,
              offset: Offset(0.0, 0.0),
            ),
          ],
        ),
        // child: Image.asset('assets/images/fab-delete.png'),
        child: Center(child: FaIcon(FontAwesomeIcons.xmark, size: 30.r, color: Colors.white)),
      ),
    );
  }

  Widget content() {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: <Widget>[
        const SizedBox(height: 10),
        const Text(
          'Add new task',
          style: TextStyle(
              fontSize: 13, fontWeight: FontWeight.w600),
        ),
        const SizedBox(height: 10),
        Container(
          margin: const EdgeInsets.only(left: 15, right: 15),
          child: Row(
            children: [
              Expanded(child: AppTextInput(
                hintText: "Task title",
                hintStyle: const TextStyle(fontSize: 22, color: Color(0xFFBCBCBC)),
                style: const TextStyle(fontSize: 22, fontStyle: FontStyle.normal),
                controller: taskTitleCtrl,
                maxLines: 1,
              ))
            ],
          ),
        ),
        const SizedBox(height: 5),

        chooseDate(),
        // Expanded(child: taskType()),
        Container(
          // height: 100,
          // width: 100,
          // color: Colors.blue.withOpacity(0.2),
          child: Obx(() => taskType()),
        ),
        20.h.hSizedBox(),

        // addSubTask(),
        10.h.hSizedBox(),

        // subTasks
        25.h.hSizedBox(),

        // addTask(),
        // 20.h.hSizedBox(),
      ],
    );
  }

  Widget taskType() {
    return Container(
      // height: 300,
      width: Get.width,
      child: GridView.builder(
        padding: EdgeInsets.symmetric(horizontal: 10.w),
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 4,
          childAspectRatio: 3/4
        ),
        itemCount: taskTypeCtrl.taskTypeList.length + 1,
        itemBuilder: (context, index) {
          if (index == taskTypeCtrl.taskTypeList.length) {
            return addTaskType();
          } else {
            return taskTypeItem(taskTypeCtrl.taskTypeList[index], index);
          }
        },
        shrinkWrap: true,
      ),
    );
  }

  Widget taskTypeItem(TaskType taskTypeItem, int index) {
    return Obx(() => GestureDetector(
      onTap: () {
        // debugPrint('akjsod');
        taskCtrl.currentTaskTypeIndex.value = index;
      },
      child: Container(
          decoration: const BoxDecoration(
            borderRadius: BorderRadius.all(
              Radius.circular(5.0),
            ),
            color: Colors.white,
          ),
          margin: const EdgeInsets.all(10),
          // height: 150.0,
          child: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Container(
                  width: 50,
                  height: 50,
                  decoration: BoxDecoration(
                      color: Color(taskTypeItem.color ?? CustomColors.YellowBackground.value).withOpacity(0.2),
                      borderRadius: const BorderRadius.all(
                        Radius.circular(50.0),
                      ),
                      border: taskCtrl.currentTaskTypeIndex.value == index
                          ? Border.all(color: Color(taskTypeItem.color ?? CustomColors.OrangeIcon.value))
                          : null
                  ),
                  child: Align(
                    child: Image.asset(
                      'assets/images/${taskTypeItem.icon}.png',
                      width: 20,
                      height: 20,
                      fit: BoxFit.cover,
                      color: Color(taskTypeItem.color ?? CustomColors.OrangeIcon.value),
                    ),
                  ),
                ),
                const SizedBox(height: 5),
                Text(
                  taskTypeItem.title ?? '',
                  style: TextStyle(
                      fontSize: 12,
                      color: taskCtrl.currentTaskTypeIndex.value == index
                          ? Color(taskTypeItem.color ?? CustomColors.TextHeaderGrey.value)
                          : CustomColors.TextHeaderGrey),
                ),
              ],
            ),
          )),
    ));
  }

  Widget addTaskType() {
    return GestureDetector(
      onTap: () {
        Get.to(() => const AddTaskType(), transition: Transition.rightToLeft);
      },
      child: Container(
        decoration: BoxDecoration(
          color: const Color(0xFFf1f3f4),
          borderRadius: BorderRadius.circular(12)
        ),
        child: Center(
          child: Icon(Icons.add_rounded, size: 50.r, color: Colors.grey),
        ),
      ),
    );
  }

  Widget chooseDate() {
    return GestureDetector(
      onTap: () async {
        DateTime? dateTime = await pickDate();

        debugPrint('dateTime: $dateTime');

        if (dateTime != null) {
          setState(() {
            newTask.expiresTime = dateTime.millisecondsSinceEpoch;
          });
        }

      },
      child: Container(
        margin: const EdgeInsets.only(left: 15, top: 15, bottom: 15),
        // color: Color(0xFFBCBCBC).withOpacity(0.2),
        width: Get.width,
        alignment: Alignment.centerLeft,
        child: Row(
          children: [
            'clock'.assetsImg(width: 30.r, fit: BoxFit.cover),
            5.w.wSizedBox(),
            Text(DateTime.fromMillisecondsSinceEpoch(newTask.expiresTime!).format('Y-m-d H:i'), style: TextStyle(fontSize: 14, fontWeight: FontWeight.bold))
          ],
        ),
      ),
    );

  }

  Widget addTask() {
    return SizedBox(
      width: ScreenUtil().screenWidth - 60.w,
      child: AppButton(
        content: 'Add task',
        gradientColors: const [
          CustomColors.BlueLight,
          CustomColors.BlueDark,
        ],

        onTap: () {

          if (taskTitleCtrl.text.isEmpty) {
            showToast('任务标题不可为空');
            return;
          }

          newTask.tid = generateRandomString(10);
          newTask.title = taskTitleCtrl.text;
          newTask.type = taskTypeCtrl.taskTypeList[taskCtrl.currentTaskTypeIndex.value].typeId;
          newTask.isDone = 0;
          newTask.remind = 0;

          taskCtrl.addTask(newTask);
          EventHelper.emit(EventBusName.taskOverViewUpdate);
          Get.back();

        },
      ),
    );
  }

  Future<DateTime?> pickDate() async {

    DateTime? dateTime = await showOmniDateTimePicker(
      context: context,
      initialDate: DateTime.now(),
      firstDate: DateTime(1600).subtract(const Duration(days: 3652)),
      lastDate: DateTime.now().add(
        const Duration(days: 3652),
      ),
      is24HourMode: false,
      isShowSeconds: false,
      minutesInterval: 1,
      secondsInterval: 1,
      borderRadius: const BorderRadius.all(Radius.circular(16)),
      constraints: const BoxConstraints(
        maxWidth: 350,
        maxHeight: 650,
      ),
      transitionBuilder: (context, anim1, anim2, child) {
        return FadeTransition(
          opacity: anim1.drive(
            Tween(
              begin: 0,
              end: 1,
            ),
          ),
          child: child,
        );
      },
      transitionDuration: const Duration(milliseconds: 200),
      barrierDismissible: true,
      selectableDayPredicate: (dateTime) {
        // Disable 25th Feb 2023
        if (dateTime == DateTime(2023, 2, 25)) {
          return false;
        } else {
          return true;
        }
      },
    );

    return dateTime;
  }

}